<?php

declare(strict_types=1);

namespace Phpben\Imi\ModuleRoute;

use Imi\Server\Http\Route\Annotation\Route as RouteAnnotation;
use Imi\Server\Http\Route\HttpRoute;
use Imi\Config;

/**
 * imi\HttpRoute
 */
class Route extends HttpRoute
{
    public function addRuleAnnotation(RouteAnnotation $annotation, $callable, array $options = []): void
    {
        $modules = Config::get("@app.beans.ModuleRoute");
        if ($modules) {
            $className = strtolower($callable->getBeanName());
            foreach ($modules as $key => $prefix) {
                if (version_compare(\PHP_VERSION, '8.0', '>=')) {
                    $is_module = str_contains($className, "\\" . $key . "\\controller\\") || str_contains($className, "\\controller\\" . $key . "\\");
                } else {
                    $is_module = strpos($className, "\\" . $key . "\\controller\\") !== false || strpos($className, "\\controller\\" . $key . "\\") !== false;
                }
                if ($is_module) {
                    $annotation->url = '/' . ltrim($prefix, '/') . $annotation->url;
                    $options['module'] = trim($prefix, '/');
                    $options['module_prefix'] = '/' . ltrim($prefix, '/');
                }
            }
        }
        parent::addRuleAnnotation($annotation, $callable, $options);
    }
}